package com.tidy.seed;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.event.EventListener;
import java.net.InetAddress;
import java.net.UnknownHostException;

@SpringBootApplication
public class SeedApplication {

    private static int serverPort;

    public static void main(String[] args) {
        SpringApplication.run(SeedApplication.class, args);
    }

    @EventListener(WebServerInitializedEvent.class)
    public void onWebServerInitialized(WebServerInitializedEvent event) {
        serverPort = event.getWebServer().getPort();
        printStartupInfo();
    }

    private void printStartupInfo() {
        try {
            String localIp = InetAddress.getLocalHost().getHostAddress();
            // 本地IP访问地址
            String ipAppUrl = "http://" + localIp + ":" + serverPort;
            // localhost访问地址
            String localhostAppUrl = "http://localhost:" + serverPort;
            // 文档地址（基于IP和localhost分别生成）
            String ipDocUrl = ipAppUrl + "/doc.html";
            String localhostDocUrl = localhostAppUrl + "/doc.html";

            System.out.println("==============================================");
            System.out.println("启动成功！");
//            System.out.println("本地IP访问地址：" + ipAppUrl);
//            System.out.println("localhost访问地址：" + localhostAppUrl);
            System.out.println("IP文档地址：" + ipDocUrl);
            System.out.println("localhost文档地址：" + localhostDocUrl);
            System.out.println("==============================================");
        } catch (UnknownHostException e) {
            // 异常时仅打印localhost地址
            String localhostAppUrl = "http://localhost:" + serverPort;
            String localhostDocUrl = localhostAppUrl + "/doc.html";
            System.out.println("==============================================");
            System.out.println("应用启动成功（获取IP失败，默认使用localhost）！");
            System.out.println("localhost访问地址：" + localhostAppUrl);
            System.out.println("localhost文档地址：" + localhostDocUrl);
            System.out.println("==============================================");
        }
    }
}